/**
 * 
 */
package com.lorizz.picpub.task.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lorizz.picpub.task.TaskExecutor;
import com.lorizz.upm.Task;
import com.lorizz.upm.TaskState;
import com.lorizz.upm.repository.Repository;

/**
 * @author wind hong
 * 
 */
public abstract class AbstractTaskExecutor<T extends Task> implements TaskExecutor<T> {

	private Log log = LogFactory.getLog(getClass());
    protected Repository upmRepository;
    private int maxFailure;

    public void setMaxFailure(int maxFailure) {
        this.maxFailure = maxFailure;
    }
    
    public void setUpmRepository(Repository upmRepository) {
        this.upmRepository = upmRepository;
    }

    @Override
    public boolean execute(T task) {
    	long start = System.currentTimeMillis();
    	boolean result = true;
        try {
            executeTask(task);
        } catch (Exception e) {
            log.error(e);
            task.setFailure(task.getFailure() + 1);
            if (task.getFailure() > maxFailure) {
                task.setState(TaskState.CANCELED);
            } else {
                task.setState(TaskState.NEW);
            }
            result = false;
            return result;
        } finally {
        	long duration =  System.currentTimeMillis() - start;
            log.debug(String.format("<%s>-<%s>-<%d>", task.getClass().getName(), result, duration));
        }
        upmRepository.remove(task);
        return result;
    }

    protected abstract void executeTask(T task);

}
